package com.tth.learn.addproperties.java;

import org.junit.Test;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;

/**
 * Java11新特性
 * @Author tth
 * @Date 2023/1/6 11:19
 */
public class Java11Test {

    /**
     * Java11新特性一：String新增的方法
     */
    @Test
    public void test1() {
        System.out.println("    ".isBlank()); // 判断当前字符串是否是空白

        System.out.println("[" + " JavaScript ".strip() + "]"); // 去除首尾空白，与trim()一样
        System.out.println("[" + " JavaScript ".stripTrailing() + "]"); // 去除尾部空白
        System.out.println("[" + " JavaScript ".stripLeading() + "]"); // 去除头部空白

        System.out.println("abc".repeat(4)); // 字符串赋值

        System.out.println("a\nbb\nc".lines().count()); // 字符串行数统计
    }

    /**
     * Java11新特性二：Optional加强
     */
    @Test
    public void test2() {

    }

    /**
     * Java11新特性三：局部变量类型推断升级--可以添加注解
     */
    @Test
    public void test3() {
        // 注：当注解去修饰变量的时候，变量的类型一定要有
        Consumer<String> con1 = (@Deprecated var t) -> System.out.println(t.toUpperCase());
    }

    /**
     * Java11新特性四：HttpClient替代HttpURLConnection
     */
    @Test
    public void test4_1() {
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder(URI.create("http://www.baidu.com")).build();
            HttpResponse.BodyHandler<String> responseHandler = HttpResponse.BodyHandlers.ofString();
            // 同步发送
            HttpResponse<String> response = client.send(request, responseHandler);
            String body = response.body();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test4_2() {
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder(URI.create("http://www.baidu.com")).build();
            HttpResponse.BodyHandler<String> responseHandler = HttpResponse.BodyHandlers.ofString();
            // 异步发送
            CompletableFuture<HttpResponse<String>> sendAsync = client.sendAsync(request, responseHandler);
            HttpResponse<String> response = sendAsync.get();
            String body = response.body();
            System.out.println(body);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
